﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ERPStudio;
using System.Data.SqlClient;
using System.Security.Cryptography;
using System.Web.Security;

namespace Administrare
{
    public partial class MembershipFrm : FrmCard
    {
        private Boolean modificatParola = false;
        private String parolaCriptata = String.Empty;
        public HashAlgorithm hashAlgo = new SHA1CryptoServiceProvider();
        private Guid _idUser = Guid.NewGuid();
        private Boolean modificatAprobat = false;
        private Boolean modificatBlocat = false;
        public MembershipFrm(Guid idUser,ModuleClass mInfo)
            : base(mInfo)
        {
            ReadOnly = true;
            _idUser = idUser;
            InitializeComponent();
            workConnString = "AdminConnectionString";
            adminDataSet.aspnet_Membership.CreateDateColumn.DefaultValue = DateTime.Now;
            adminDataSet.aspnet_Membership.PasswordFormatColumn.DefaultValue = 0;
            adminDataSet.aspnet_Membership.IsApprovedColumn.DefaultValue = false;
            adminDataSet.aspnet_Membership.IsLockedOutColumn.DefaultValue = false;
            adminDataSet.aspnet_Membership.LastLoginDateColumn.DefaultValue = DateTime.Now;
            adminDataSet.aspnet_Membership.LastPasswordChangedDateColumn.DefaultValue = DateTime.Now;
            adminDataSet.aspnet_Membership.LastLockoutDateColumn.DefaultValue = DateTime.Now;
            adminDataSet.aspnet_Membership.FailedPasswordAttemptCountColumn.DefaultValue = 0;
            adminDataSet.aspnet_Membership.FailedPasswordAttemptWindowStartColumn.DefaultValue = DateTime.Now;
            adminDataSet.aspnet_Membership.FailedPasswordAnswerAttemptCountColumn.DefaultValue = 0;
            adminDataSet.aspnet_Membership.FailedPasswordAnswerAttemptWindowStartColumn.DefaultValue = DateTime.Now;
            adminDataSet.aspnet_Membership.UserIDUpdateColumn.DefaultValue = mInfo.UserID;

            this.HandleAfterAdd += new AfterAddHandler(MembershipFrm_HandleAfterAdd);

        }

        void MembershipFrm_HandleAfterAdd(object sender, DataGridViewCellEventArgs args)
        {
            AdminDataSet.aspnet_MembershipRow rm = ((DataRowView)aspnet_MembershipBindingSource.Current).Row
                      as AdminDataSet.aspnet_MembershipRow;
            AdminDataSet.aspnet_UsersRow ru = ((DataRowView)aspnet_UsersBindingSource.Current).Row
                as AdminDataSet.aspnet_UsersRow;
            rm.ApplicationId = ru.ApplicationId;
            rm.UserId = ru.UserId;
        }

        private void MembershipFrm_Load(object sender, EventArgs e)
        {
            AddBindingSource(aspnet_MembershipBindingSource);
            listTableAdaptor.Add(aspnet_MembershipTableAdapter.Adapter);
            
            SqlConnection con = DeschideConexiune(workConnString);
            this.aspnet_MembershipTableAdapter.Connection = con;
            this.aspnet_MembershipTableAdapter.FillByUserID(adminDataSet.aspnet_Membership, _idUser);
            this.aspnet_UsersTableAdapter.Connection = con;
            this.aspnet_UsersTableAdapter.FillByUserID(this.adminDataSet.aspnet_Users,_idUser);
            InchideConexiune(con);
            if (aspnet_MembershipBindingSource.Count == 0)
            {
                ReadOnly = false;
                Adauga(this, null);
                ReadOnly = true;
            }

            modificatParola = false;
            modificatAprobat = false;
            modificatBlocat = false;
        }

        private Byte[] GetHash(String parola, String salt)
        {
            System.Security.Cryptography.RNGCryptoServiceProvider.Create();
            Byte[] NewPasswordBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(parola);
            Byte[] saltBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(salt);
            Byte[] combinedBytes = new Byte[NewPasswordBytes.Length + saltBytes.Length];
            System.Buffer.BlockCopy(NewPasswordBytes, 0, combinedBytes, 0, NewPasswordBytes.Length);
            System.Buffer.BlockCopy(saltBytes, 0, combinedBytes, NewPasswordBytes.Length, saltBytes.Length);         
            Byte[] hash = hashAlgo.ComputeHash(combinedBytes);
            for (int i = 0; i < hash.Length; i++)
                if (hash[i] == 0)
                    hash[i] = (Byte)' ';
            return hash;
        
        }

        override public void Salvare(object sender, EventArgs args)
        {
            
            if (passwordTB.Text != passwordTB2.Text) 
            {
                MessageBox.Show("Cele doua parole introduse nu sunt identice!","Eroare",
                           MessageBoxButtons.OK,
                           MessageBoxIcon.Hand);
                return;
            }

            MembershipUser muser = Membership.GetUser(_idUser, false);
            if (muser != null)
            {
                if (modificatAprobat)
                {
                    muser.IsApproved = isApprovedCheckBox.Checked;
                    Membership.UpdateUser(muser);
                }

                if (modificatBlocat)
                {
                    muser.UnlockUser();
                    Membership.UpdateUser(muser);
                }
                if (modificatParola)
                {
                    try
                    {
                        String Parola = muser.ResetPassword();
                        muser.ChangePassword(Parola, passwordTB.Text);
                        Membership.UpdateUser(muser);
                    }
                    catch (Exception ex)
                    {
                        TrateazaExceptie(ex);
                        return;
                    }
                }

            }
            else
            {
                //try
                //{
                //    MembershipUser mu = Membership.CreateUser(NumeUtilizatorTB.Text, passwordTB.Text);
                //    Membership.UpdateUser(mu);
                //}
                 
                //catch (Exception ex)
                //{
                //    TrateazaExceptie(ex);
                //    return;
                //}
                ReadOnly = false;
                base.Salvare(this, args);
                ReadOnly = true;
                if (EroareSalvare)
                {
                    SetStatus("Eroare salvare: " + DateTime.Now.ToString());
                    return;
                }
                else
                    SetStatus("S-au adaugat 1 inregistrari la: " + DateTime.Now.ToString());
                

            }


            //DataRow[] updatedRows = adminDataSet.aspnet_Membership.Select(null, null, DataViewRowState.ModifiedCurrent);
            //if (updatedRows.Length != 0)
            //{
            //    foreach (DataRow dr in updatedRows)
            //        dr["UserIDUpdate"] = ModuleInfo.UserID;
            //}
            //base.Salvare(this, args);
            //if (EroareSalvare)
            //    return;


            /*AdminDataSet.aspnet_ApplicationsRow rd = ((DataRowView)aspnet_ApplicationsBindingSource.Current).Row as AdminDataSet.aspnet_ApplicationsRow;
            Guid cGui = rd.ApplicationId;
            SqlConnection con = DeschideConexiune(workConnString);
            this.aspnet_ApplicationsTableAdapter.Connection = con;
            this.aspnet_ApplicationsTableAdapter.Fill(this.adminDataSet.aspnet_Applications);
            InchideConexiune(con);
            int poz = aspnet_ApplicationsBindingSource.Find("ApplicationId", cGui);
            if (poz > 0)
                aspnet_ApplicationsBindingSource.Position = poz;
             * */

            
        }

        private void passwordTB_TextChanged(object sender, EventArgs e)
        {
            //Byte[] ret = GetHash(passwordTB.Text, passwordSaltTB.Text);
            //AdminDataSet.aspnet_MembershipRow rd = ((DataRowView)aspnet_MembershipBindingSource.Current).Row
            //    as AdminDataSet.aspnet_MembershipRow;
            //rd.Password = ASCIIEncoding.ASCII.GetString(ret);
            modificatParola = true;
        }

        private void isApprovedCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            modificatAprobat = true;
        }

        private void isLockedOutCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            modificatBlocat = true;
        }
    }
}
